﻿using System;
using System.Collections.Generic;
using System.Web;
using MAF.CRUD;


namespace MAF.Common
{
    public abstract class BaseHandler<T> where T : IID<Guid>, new()
    {
        public virtual void Add()
        {
            T info = MAF.Common.ObjectConverter.ToObject<T>(HttpContext.Current.Request.Form);
            GetService().Add(info);
        }

        public virtual void Update()
        {
            T info = MAF.Common.ObjectConverter.ToObject<T>(HttpContext.Current.Request.Form);
            GetService().Update(info);
        }

        public virtual int Delete()
        {
            string ids = HttpContext.Current.Request.Form["Id"];
            return GetService().Delete(ids);
        }

        public virtual T Show()
        {
            string id = HttpContext.Current.Request.QueryString["Id"];
            return GetService().Show(new Guid(id));
        }

        public virtual IList<T> Index()
        {
            PageInfo p;
            return Index(out p);
        }

        public virtual IList<T> Index(out PageInfo page)
        {
            ICRUD<T> svc = GetService();
            BaseQueryVo vo = BaseQueryVo.Parse(HttpContext.Current.Request.QueryString);
            IList<T> list = svc.Index(vo);

            page = vo.Page;         // 返回page
            return list;            // 返回list
        }

        /// <summary>
        /// 提供使用固定ParentId的方法
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public virtual IList<T> Index(Guid parentId)
        {
            BaseQueryVo vo = new BaseQueryVo();
            vo.ParentId = parentId.ToString();
            return GetService().Index(vo);
        }

        protected abstract ICRUD<T> GetService();
    }
}
